package com.campol.extlogger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;



public class ExtStorageHelper {

	private static final String TAG = ExtStorageHelper.class.getName();
	private static final String EXTERNAL_FKTRL_DIR = "/fartkontrollerne/";
	private static final String logFile = "logfile.txt";
	
	/**
	 * checks for sd-card mounted
	 * 
	 * @return true for mounted sd-card
	 */
	private static boolean isMounted() {
		String sdCardState = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(sdCardState)) {
			return true;
		}
		return false;
	}
	
	/**
	 * Writes a recipe to sd-card
	 * @return true for success result
	 */
	public static boolean writePlainTextToSdCard(String message) {
		if (!isMounted()) {
			Log.d(TAG, "Fail to write to sd-card: sd-card unmounted");
			return false;
		}
		
		File cookBookDir = new File(Environment.getExternalStorageDirectory() + EXTERNAL_FKTRL_DIR);
		if (!cookBookDir.exists()) {
			if (!cookBookDir.mkdir()) {
				return false;
			}
		} 

		File log = new File(cookBookDir.getPath(),logFile);
		if (!log.exists()) {
			try {
				if (!log.createNewFile()) return false;
			} catch (IOException e) {
				return false;
			}
		}
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(log));
			bw.append(message);
			bw.newLine();
			bw.close();
		} catch (IOException e) {
			return false;
		}
		
		return true;
	}
}